const fs = require('fs');
const path = require('path');
const { ensureDirectory, writeJsonFile, readJsonFile, getCurrentTimestamp } = require('./utils');

/**
 * 任务日志记录器
 * @class TaskLogger
 */
class TaskLogger {
    /**
     * 构造函数
     * @param {string} logDir - 日志目录
     */
    constructor(logDir = './download-logs') {
        this.logDir = logDir;
        this.taskStateFile = path.join(logDir, 'tasks-state.json');
        this.downloadLogFile = path.join(logDir, 'download-history.log');

        ensureDirectory(this.logDir);
    }

    /**
     * 记录任务状态
     * @param {string} taskId - 任务ID
     * @param {Object} state - 任务状态
     */
    logTaskState(taskId, state) {
        const allStates = this.getAllTaskStates();
        allStates[taskId] = state;
        writeJsonFile(this.taskStateFile, allStates);
    }

    /**
     * 删除任务状态记录
     * @param {string} taskId - 任务ID
     */
    removeTaskState(taskId) {
        const allStates = this.getAllTaskStates();
        delete allStates[taskId];
        writeJsonFile(this.taskStateFile, allStates);
    }

    /**
     * 获取所有任务状态
     * @return {Object} 所有任务状态
     */
    getAllTaskStates() {
        return readJsonFile(this.taskStateFile) || {};
    }

    /**
     * 记录下载事件
     * @param {string} message - 日志消息
     * @param {Object} [data] - 附加数据
     */
    logEvent(message, data = {}) {
        const logEntry = {
            timestamp: getCurrentTimestamp(),
            message,
            ...data
        };

        fs.appendFileSync(
            this.downloadLogFile,
            JSON.stringify(logEntry) + '\n',
            'utf-8'
        );
    }

    /**
     * 清除所有日志
     */
    clearAllLogs() {
        if (fs.existsSync(this.taskStateFile)) {
            fs.unlinkSync(this.taskStateFile);
        }
        if (fs.existsSync(this.downloadLogFile)) {
            fs.unlinkSync(this.downloadLogFile);
        }
    }
}

module.exports = TaskLogger;